<?php
/*
Plugin Name: RCJ Login Plugin
Plugin URI: 
Description: 
Version: 0.9.0
Author: Heriniaina Eugene
Author URI: http://hery.serasera.org
*/

ini_set('memory_limit', "32M");


// Includes
require_once("rcj_auth/nusoap.php");

//require_once();

// *** Begin Admin Config Functions *** //
add_action('init', 'rcj_signup');

function rcj_signup() {
	if($_SERVER["REQUEST_URI"] == "/wp-signup.php") {
		if($redirect = get_site_option("rcjSignupURL")) {
			echo "
				<script language=\"javascript\"
				type=\"text/javascript\">
				<!--
				window.location.replace(
				\"$redirect\");
				-->
				</script>
			";
			exit;
		}
	}


	if($_GET['loggedout'] == "true") {
			echo "
				<script language=\"javascript\"
				type=\"text/javascript\">
				<!--
				window.location.replace(
				\"http://blog.rcj.org\");
				-->
				</script>
			";
			exit;
	}


}




add_action('admin_menu', 'rcj_addmenu');
function rcj_addmenu() {
	$objCurrUser = wp_get_current_user();
	$objUser = wp_cache_get($objCurrUser->id, 'users');
	if (function_exists('add_options_page') && is_site_admin($objUser->user_login)) {
		add_options_page('RCJ Authentication Options', 'RCJ Options', 9, basename(__FILE__), 'rcjOptionsPanel');
	}
}

add_action('admin_head', 'rcj_addcss');
function rcj_addcss() {
	echo "<link rel='stylesheet' href='" . get_settings('siteurl') . "/wp-content/plugins/rcj_auth.css' media='screen' type='text/css' />";
}

function rcjOptionsPanel() {
	if($_POST['rcjOptionsSave']) {
		update_site_option('rcjSignupURL', $_POST['rcjOptionsSignupURL']);
		update_site_option('rcjApiKey', $_POST['rcjOptionsApiKey']);
		update_site_option('rcjEndPoint', $_POST['rcjOptionsEndPoint']);
		update_site_option('rcjAuth', $_POST['rcjOptionsAuth']);
		
		echo "<div class='updated'><p>Saved Options!</p></div>";
	}
	
	$rcjSignupURL 			= get_site_option("rcjSignupURL");
	$rcjApiKey 			= get_site_option("rcjApiKey");
	$rcjEndPoint		= get_site_option("rcjEndPoint");
	$rcjAuth			= get_site_option("rcjAuth");
	$rcjCookieMarker	= get_site_option("rcjCookieMarker");

	if($rcjAuth) {
		$tChecked = "checked";
	}
	else {
		$fChecked = "checked";
	}
	
	echo <<<rcjForm
	<div class="wrap">
	<h2>rcj Authentication Options</h2>
	<form method="post" id="rcj_auth_options">
		<fieldset class="options">
		<legend>General Server Settings</legend>
		
		<div class="row">
			<span class="description">RCJ Webservice</span>
			<span class="element">
				<input type='text' name='rcjOptionsEndPoint' value='$rcjEndPoint' style='width: 300px;' /><br />
				<em>The URI of the webservice.</em>
			</span>
		</div>
		
		<div class="row">
			<span class="description">Api Key</span>
			<span class="element">
				<input type='text' name='rcjOptionsApiKey' value='$rcjApiKey' style='width: 300px;' /><br />
				<em>You should have a key to use rcj webservice</em>
			</span>
		</div>
		
		<div class="row">
			<span class="description">RCJ Signup Page</span>
			<span class="element">
				<input type='text' name='rcjOptionsSignupURL' value='$rcjSignupURL' style='width: 300px;' /><br />
				<em>When people click on Signup Page</em>
			</span>
		</div>

		<div class="row">
			<span class="description">Enable rcj plugin?</span><br />
			<span class="element">
				<input type='radio' name='rcjOptionsAuth' value='1' $tChecked/> Yes
				<input type='radio' name='rcjOptionsAuth' value='0' $fChecked/> No
			</span>
		</div>
		
		<p class="submit"><input type="submit" name="rcjOptionsSave" value="Save" /></p>
		</fieldset>
	</form>
	</div>
rcjForm;
}
// *** End Admin Config Functions *** //


// *** Begin User Auth Functions *** //

// This will disabled the chage password dialogs.
// There is no docs so this is the only way i can think of to disable this 'feature'
if (get_site_option("rcjAuth")) : 
add_filter('show_password_fields', 'getFalse');
function getFalse() {
	return false;
}
endif;

if (get_site_option("rcjAuth")) {
function wp_login($username, $password, $already_md5 = false) {
	global $wpdb, $error, $current_site, $current_user, $base;
	
	//Make sure we always use lowercase usernames.
	$username = strtolower($username);
	
	$rcjAuth 			= get_site_option("rcjAuth");
	$rcjApiKey 			= get_site_option("rcjApiKey");
	$rcjEndPoint		= get_site_option("rcjEndPoint");
	
	if(!$username) {
		$error = __('<strong>Error</strong>: The username field is empty.');
		return false;
	}
	
	if(!$password) {
		$error = __('<strong>Error</strong>: The password field is empty.');
		return false;
	}
	
	//Bassically if we are already logged in and we try to relogin.
	if ($current_user->data->user_login == $username) {
		return true;
	}
	
	$login = get_userdatabylogin($username);


	//everything is ok
	
	if ( ($already_md5 && $login->user_login == $username && md5($login->user_pass) == $password) || ($login->user_login == $username && $login->user_pass == md5($password)) ) {
		return true;
	}
	
	//only username is ok => check from webservice and update the password
	if($login->user_login == $username) {
		$client = new soapclient($rcjEndPoint, true);
		$err = $client->getError();

		
		if($err) {
			$error = __('<strong>Error</strong>: Wrong password.');
			Return false;
		}

		$param = array('wsid' => "rcj", 'username' => $username, 'password' => $password);
		$result = $client->call('getUser', $param);
		
		if ($client->fault) {
			$error = __('<strong>Error</strong>: Wrong password.');
			return false;
		} else {
			if($result[loggedin] == true) {
				$query = "UPDATE $wpdb->users SET user_pass='" . md5($password) . "' WHERE ID = '$login->ID'";
				$query = apply_filters('update_user_query', $query);
				$wpdb->query( $query );
				Return true;
			} else {
				$error = __('<strong>Error</strong>: Wrong password.');
				return false;
			}
		}
	} else {
		// a complete new user from the webservice
	
		$client = new soapclient($rcjEndPoint, true);
		$err = $client->getError();

		
		if($err) {
			Return false;
		}

		$param = array('wsid' => "rcj", 'username' => $username, 'password' => $password);
		$result = $client->call('getUser', $param);
		
		if ($client->fault) {
			$error = __('<strong>Error</strong>: Wrong password.');
			return false;
		} else {
			if($result[loggedin] == true) {

				// call the registration function to create a wordpress user account for this
				// successfully authenticated user
				require_once( ABSPATH . WPINC . '/registration.php');
				
				if ( !username_exists( $username ) ) {
					//Create the user
					//$sPassword = generate_random_password();
					$user_id = wpmu_create_user( $username, $password, $result[email] );
					
					if (!$user_id) {
						$error = __('<strong>Error</strong>: Account Creation Failed.');
						return false;
					}
					
					//Update their first and last name from ldap
					update_usermeta( $user_id, 'first_name', $result[firstname] );
					update_usermeta( $user_id, 'last_name', $result[lastname] );
					
					//This is for plugin events
					do_action( 'wpmu_new_user', $user_id );
					do_action('wpmu_activate_user', $user_id, $password);
					
					$domain = strtolower( wp_specialchars( $username ) );
					if( constant( "VHOST" ) == 'yes' ) {
						$newdomain = $domain . "." . $current_site->domain;
						$path = $base;
					} else {
						$newdomain = $current_site->domain;
						$path = $base . $domain . '/';
					}
					
					
					//Becuase WPMU has a bug in the create blog function we need this code 
					//To prevent errors with the wpmu_create_blog function.  See Ticket #184
					$result = $wpdb->query( "CREATE TABLE wp_" . $user_id . "_options (option_id bigint(20) NOT NULL auto_increment, blog_id int(11) NOT NULL default 0, option_name varchar(64) NOT NULL default '', option_can_override enum('Y','N') NOT NULL default 'Y', option_type int(11) NOT NULL default 1, option_value longtext NOT NULL, option_width int(11) NOT NULL default 20, option_height int(11) NOT NULL default 8, option_description tinytext NOT NULL, option_admin_level int(11) NOT NULL default 1, autoload enum('yes','no') NOT NULL default 'yes', PRIMARY KEY  (option_id,blog_id,option_name), KEY option_name (option_name)) ENGINE=MyISAM DEFAULT CHARSET=utf8;" );
					
					//Create and update the users blog.
					$meta = apply_filters('signup_create_blog_meta', array ('lang_id' => 'en', 'public' => 1));
					$blog_id = wpmu_create_blog($newdomain, $path, $username . "'s blog", $user_id, $meta);
					do_action('wpmu_activate_blog', $blog_id, $user_id, $password, $username . "'s blog", $meta);
					
					//Must recreated the login object for our shiny NEW users.
					$login = get_userdatabylogin($username);
					
					//Setup redirection to users home directory.
					if (!strpos($_REQUEST['redirect_to'], $username)) {
						$_REQUEST['redirect_to'] = $username . "/" . $_REQUEST['redirect_to'];
					}
				} elseif ( !username_exists( $username ) && !$rcjCreateAcct ) {
					$error = __('<strong>Error</strong>: Local account does not exist.');
					return false;
				}

			} else {
				$error = __('<strong>Error</strong>: Wrong login and password.');
				return false;
			}
		}
				
		//At this point we must have a login object!
		//I dont see how we couldn't but just in case.
		if (!$login) {
			$error = __('<strong>Error</strong>: Unknown Near Line 274 rcj_auth.php.');
			return false;
		}
		
		//Added to atempt to recreate login correctly
		//I think this is for account suspentions
		$primary_blog = get_usermeta( $login->ID, "primary_blog" );
		if( $primary_blog ) {
			$details = get_blog_details( $primary_blog );
			if( is_object( $details ) ) {
				if( $details->archived == 1 || $details->spam == 1 || $details->deleted == 1 ) {
					$error = __('<strong>Error</strong>: Blog suspended.');
					return false;
				}
			}
		}
				

		// Bad Coding Practiace
		// We can get to this point in code and exit without a status.
		// This is why we dont exit at multipul points boys and girls.
		return false;
	} // End if (LDAP_ENABLED)

		//We are Not using LDAP So we need to auth normally 
		//This is all original code pulled from the pluggable.php 
		//file located in the wp-plugins folder.  Comments were 
		//added to help figure out what is going on.
		
		//Now I think this is trying to get the users data. 
		//I think the site admin and domain admins are stored 
		//seperatly from normal users??? Just guessing as there 
		//is NO DOCUMENTATION!!!
		//This entire code block seems a bit useless to me.  Definitly not needed if we use ldap.
		if (!$login) {
			if( is_site_admin( $username ) ) {
				//If Site Admin
				//FYI This does exactly the same thing as $login = get_userdatabylogin( $username );
				//which has already been done above?!?
				unset( $login );
				$userdetails = get_userdatabylogin( $username );
				$login->user_login = $username;
				$login->user_pass = $userdetails->user_pass;
			} else {
				//If Domain Admin
				$admins = get_admin_users_for_domain();
				reset( $admins );
				while( list( $key, $val ) = each( $admins ) ) 
				{ 
					if( $val[ 'user_login' ] == $username ) {
						unset( $login );
						$login->user_login = $username;
						$login->user_pass  = $val[ 'user_pass' ];
					}
				}
			}
		}
		
		if (!$login) {
			//If we didnt find a user originally and we didnt get one from the above code...
			$error = __('<strong>Error</strong>: Wrong username.');
			return false;
		} else {
			//Setup some kind of default blog for the user...
			$primary_blog = get_usermeta( $login->ID, "primary_blog" );
			if( $primary_blog ) {
				$details = get_blog_details( $primary_blog );
				if( is_object( $details ) ) {
					if( $details->archived == 1 || $details->spam == 1 || $details->deleted == 1 ) {
						$error = __('<strong>Error</strong>: Blog suspended.');
						return false;
					}
				}
			}
			
			//Setup redirection to users home directory.
			if (!strpos($_REQUEST['redirect_to'], $username)) {
				$_REQUEST['redirect_to'] = $username . "/" . $_REQUEST['redirect_to'];
			}
			
			// If the password is already_md5, it has been double hashed.
			// Otherwise, it is plain text.
			if ( ($already_md5 && $login->user_login == $username && md5($login->user_pass) == $password) || ($login->user_login == $username && $login->user_pass == md5($password)) ) {
				return true;
			} else {
				$error = __('<strong>Error</strong>: Incorrect password.');
				$pwd = '';
				return false;
			}
		}
	}
}

/*
if (get_site_option("rcjAuth")) : 
function wp_setcookie($username, $password, $already_md5 = false, $home = '', $siteurl = '') {
	$rcjCookieMarker = get_site_option("rcjCookieMarker");
	$rcjAuth = get_site_option("rcjAuth");
	
	if(($rcjAuth) && ($username != "admin")) {
		// This hanldes all ldap users who are not admin
		$password = md5($username).md5($rcjCookieMarker);
	}
	else {
		if(!$already_md5) {
			//Basiclly this will check admin or users when ldap is disabled.
			//Some Clever modfication can be done to add this code under the if part
			//of this if / else above to allow both ldap and local users to login.
			$password = md5( md5($password) ); // Double hash the password in the cookie.
		}
	}
	
	// From Here Down the File is Stock Form pluggable.php after #125: login-cookie-01.patch
	if ( $remember )
		$expire = time() + 31536000;
	else
		$expire = 0;

	global $base;
	setcookie(USER_COOKIE, $username, $expire, $base, COOKIE_DOMAIN);
	setcookie(PASS_COOKIE, $password, $expire, $base, COOKIE_DOMAIN);
}
endif;
*/
// *** End User Auth Functions *** //



?>
